import { computed, reactive, Ref, ref, set } from 'vue'
import config from '@/config'
import { DocData } from '@/types'
import useDocState from './useDocState'
import useScrollState from '@/utils/compositions/useScrollState'
import useZoom from './useZoom'

/** 文档布局状态 */
interface LayoutState {
  ridingArea: boolean
}

/** 合同文档布局控制 */
export default function useLayout({
  scrollState,
  doc,
  state,
  zoom,
  ridingWidth,
  pageSpacing
}: {
  scrollState: ReturnType<typeof useScrollState>
  doc: Ref<DocData>
  state: ReturnType<typeof useDocState>
  zoom: ReturnType<typeof useZoom>
  ridingWidth: Ref<number>
  pageSpacing: Ref<number>
}) {
  /** 布局状态 */
  const layoutStore = ref({} as Record<string, LayoutState>)

  /** 获取文档宽度 */
  const docWidth = computed(() => state.pageSum.maxWidth)

  /** 骑缝区域是否展开 */
  const ridingActive = computed({
    get: () => !!layoutStore.value[doc.value.id]?.ridingArea,

    set(val: boolean): void {
      const store = layoutStore.value
      const docId = doc.value.id
      const docState = store[docId]

      if (!docState) {
        set(store, docId, { ridingArea: val })
      } else {
        docState.ridingArea = val
      }
    }
  })

  /** 文档区域宽度，包含骑缝控件 */
  const docAreaWidth = computed(() => docWidth.value + (ridingActive.value ? ridingWidth.value : 0))

  /** 文档区域高度，包含页面间距 */
  const docAreaHeight = computed(() => {
    const { totalHeight, pageCount } = state
    return (totalHeight || 0) + (pageSpacing.value * (pageCount + 1)) / zoom.level
  })

  /** 文档区域缩放宽度 */
  const docAreaZoomWidth = computed(() => docAreaWidth.value * zoom.level)

  /** 是否有横向滚动条 */
  const hasScrollerX = computed(() => docAreaZoomWidth.value > scrollState.width)

  /** 纵向工具栏是否相对滚动区域固定，否则相对文档区域固定 */
  const isToolsYFixed = computed(() => docAreaZoomWidth.value + config.toolsWrapperWidth * 2 >= scrollState.width)

  /** 布局 */
  return reactive({
    ridingWidth,
    ridingActive,
    docWidth,
    docAreaWidth,
    docAreaHeight,
    docAreaZoomWidth,
    pageSpacing,
    hasScrollerX,
    isToolsYFixed
  })
}
